﻿using CBS.APP;
using CBS.DB.CBSEntity;
using CBS.Model.Enum;
using CBS.Model.ManageModel;
using CBS.Model.UIModel;
using CBS.Model.ViewModel;
using Microsoft.Win32;
using NPOI.HPSF;
using NPOI.Util.Collections;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CBS.Desktop.FormPage
{
    /// <summary>
    /// ImportStudentSignDetail.xaml 的交互逻辑
    /// </summary>
    public partial class ImportStudentSignDetail : Window
    {
        private bool _isSemesterDataBound = false;
        private bool _isGradeDataBound = false;
        private bool _isClassDataBound = false;
        private bool _isCourseDataBound = false;

        private ImportStudentSignDetailFormCondition _formCondition;
        //public ImportStudentSignDetail()
        //{
        //    InitializeComponent();

        //    LoadCondation();
        //}

        public ImportStudentSignDetail(ImportStudentSignDetailFormCondition formCondition)
        {
            InitializeComponent();
            this._formCondition = formCondition;
            LoadCondation();
        }

        private async void LoadCondation()
        {
            // 加载 ComboBox 数据
            await LoadDataAsync();

            // 查询 Grid 数据
            BindLesson();
        }

        private async Task LoadDataAsync()
        {
            // 使用 Task.WhenAll 等待所有 ComboBox 数据加载完成
            var tasks = new List<Task>
            {
                BindSemester(),
                BindGrade(),
                BindClass(),
                BindCourse()
            };

            await Task.WhenAll(tasks);
        }

        private async Task BindSemester()
        {
            try
            {
                var list = await Task.Run(() => SemesterApp.GetSelectList());

                if (list.Count == 0)
                {
                    return;
                }


                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Semester.ItemsSource = list;

                }));
                if (this._formCondition == null)
                {
                    cb_Semester.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Semester.Items
                                            .Cast<SemesterSelectModel>()
                                            .ToList()
                                            .FindIndex(item => item.SemesterId == this._formCondition.SemesterId);

                    cb_Semester.SelectedIndex = index;
                }

                // 设置标志为 true
                _isSemesterDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async Task BindGrade()
        {
            try
            {
                var list = await Task.Run(() => GradeApp.GetSelectList());

                list.Insert(0, new GradeViewModel { GradeId = 0, GradeName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Grade.ItemsSource = list;
                }));
                if (this._formCondition == null)
                {
                    cb_Grade.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Grade.Items
                                            .Cast<GradeViewModel>()
                                            .ToList()
                                            .FindIndex(item => item.GradeId == this._formCondition.GradeId);

                    cb_Grade.SelectedIndex = index;
                }
                // 设置标志为 true
                _isGradeDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindClass()
        {
            try
            {
                var list = await Task.Run(() => ClassApp.GetSelectList());

                list.Insert(0, new ClassViewModel { ClassId = 0, ClassName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Class.ItemsSource = list;
                }));
                if (this._formCondition == null)
                {
                    cb_Class.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Class.Items
                                            .Cast<ClassViewModel>()
                                            .ToList()
                                            .FindIndex(item => item.ClassId == this._formCondition.ClassId);

                    cb_Class.SelectedIndex = index;
                }


                // 设置标志为 true
                _isClassDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindCourse()
        {
            try
            {
                var list = await Task.Run(() => CourseApp.GetSelectList());

                list.Insert(0, new CourseViewModel { CourseId = 0, CourseName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Course.ItemsSource = list;

                }));
                if (this._formCondition == null)
                {
                    cb_Course.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Course.Items
                                            .Cast<CourseViewModel>()
                                            .ToList()
                                            .FindIndex(item => item.CourseId == this._formCondition.CourseId);

                    cb_Course.SelectedIndex = index;
                }


                // 设置标志为 true
                _isCourseDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }


        private async void BindLesson()
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;
                var list = await Task.Run(() => LessonApp.GetSelectList(semesterId, gradeId, classId, courseId));

                if (list.Count == 0)
                {
                    return;
                }

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Lesson.ItemsSource = list;
                }));
                if (this._formCondition == null)
                {
                    cb_Lesson.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Lesson.Items
                                            .Cast<LessonSelectModel>()
                                            .ToList()
                                            .FindIndex(item => item.LessonId == this._formCondition.LessonId);
                    cb_Lesson.SelectedIndex = (index == -1 ? 0 : index);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Mouse.OverrideCursor = Cursors.Wait;

                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int lessonId = ((LessonSelectModel)cb_Lesson.SelectedItem).LessonId;

                int importType = tb_ImportEnum.SelectedIndex;
                bool result = false;
                string msg = string.Empty;

                switch (importType)
                {
                    case 1:
                        string signInStudent = tb_SignInStudentName.Text.Trim();
                        string tasterSignInStudent = tb_TasterSignInStudentName.Text.Trim();
                        string introduceStudent = tb_IntroduceStudentName.Text.Trim();
                        result = StudentSignInApp.ImportStudentSignIn(signInStudent, tasterSignInStudent, introduceStudent, semesterId, lessonId, out msg);
                        break;
                    case 2:
                        string supplementStudent = tb_SupplementStudentName.Text.Trim();
                        string supplementStartTimeStr = tb_SupplementStartTime.Text.Trim();
                        string supplementEndTimeStr = tb_SupplementEndTime.Text.Trim();


                        if (string.IsNullOrWhiteSpace(supplementStartTimeStr) && string.IsNullOrWhiteSpace(supplementEndTimeStr))
                        {
                            result = StudentSignInApp.ImportSupplementStudent(supplementStudent, null, null, semesterId, lessonId, out msg);
                        }
                        else
                        {
                            DateTime supplementStartTime, supplementEndTime;
                            if (string.IsNullOrWhiteSpace(supplementStartTimeStr) && !string.IsNullOrWhiteSpace(supplementEndTimeStr))
                            {
                                MessageBox.Show(this, "请输入开始时间。", "操作失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                                return;
                            }
                            else if (!string.IsNullOrWhiteSpace(supplementStartTimeStr) && string.IsNullOrWhiteSpace(supplementEndTimeStr))
                            {
                                MessageBox.Show(this, "结束时间。", "操作失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                                return;
                            }
                            else if (!DateTime.TryParse(supplementStartTimeStr, out supplementStartTime))
                            {
                                MessageBox.Show(this, "开始时间输入格式错误。", "操作失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                                return;
                            }
                            else if (!DateTime.TryParse(supplementEndTimeStr, out supplementEndTime))
                            {
                                MessageBox.Show(this, "结束时间输入格式错误。", "操作失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                                return;
                            }
                            else
                            {
                                result = StudentSignInApp.ImportSupplementStudent(supplementStudent, supplementStartTime, supplementEndTime, semesterId, lessonId, out msg);
                            }
                        }
                        break;
                    default:
                        string noSignInStudent = tb_NoSignInStudentName.Text.Trim();
                        result = StudentSignInApp.ImportNoStudentSignIn(noSignInStudent, semesterId, lessonId, out msg);
                        break;
                }

                if (result)
                {
                    this.DialogResult = true;
                }
                else
                {
                    MessageBox.Show(this, msg, "操作失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                Mouse.OverrideCursor = null;
            }
            catch (Exception ex)
            {
                Mouse.OverrideCursor = null;
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void tb_NoSignInStudentName_TextChanged(object sender, TextChangedEventArgs e)
        {
            string context = tb_NoSignInStudentName.Text.Trim();
            context = context.Replace("，", ",");
            context = context.TrimEnd(',');
            string[] originNameArray = context.Split(',');
            int nameCount = originNameArray.Length;
            string[] repeatArray = originNameArray.Distinct().ToArray();
            int repeatCount = repeatArray.Length;
            if (repeatCount < nameCount)
            {
                tb_NoSignInClipMsg.Text = $"检测到{nameCount}个学生姓名，有{nameCount - repeatCount}个重名。";
                Color color = (Color)ColorConverter.ConvertFromString("#FFE13333");
                tb_NoSignInClipMsg.Foreground = new SolidColorBrush(color);
                btn_Submit.IsEnabled = false;
            }
            else
            {
                tb_NoSignInClipMsg.Text = $"检测到{nameCount}个学生姓名。";
                tb_NoSignInClipMsg.Foreground = Brushes.Black;
                btn_Submit.IsEnabled = true;
            }
        }

        private void cb_Semester_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isSemesterDataBound)
                return;

            BindLesson();
        }

        private void cb_Grade_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isGradeDataBound)
                return;

            BindLesson();
        }
        private void cb_Class_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isClassDataBound)
                return;

            BindLesson();
        }
        private void cb_Course_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isCourseDataBound)
                return;

            BindLesson();
        }

        private void tb_SignInStudentName_TextChanged(object sender, TextChangedEventArgs e)
        {
            string context = tb_SignInStudentName.Text.Trim();
            context = context.Replace("，", ",");
            context = context.TrimEnd(',');
            string[] originNameArray = context.Split(',');
            int nameCount = originNameArray.Length;
            string[] repeatArray = originNameArray.Distinct().ToArray();
            int repeatCount = repeatArray.Length;
            if (repeatCount < nameCount)
            {
                tb_SignInClipMsg.Text = $"检测到{nameCount}个学生姓名，有{nameCount - repeatCount}个重名。";
                Color color = (Color)ColorConverter.ConvertFromString("#FFE13333");
                tb_SignInClipMsg.Foreground = new SolidColorBrush(color);
                btn_Submit.IsEnabled = false;
            }
            else
            {
                tb_SignInClipMsg.Text = $"检测到{nameCount}个学生姓名。";
                tb_SignInClipMsg.Foreground = Brushes.Black;
                btn_Submit.IsEnabled = true;
            }
        }

        private void tb_TasterSignInStudentName_TextChanged(object sender, TextChangedEventArgs e)
        {
            string context = tb_TasterSignInStudentName.Text.Trim();
            context = context.Replace("，", ",");
            context = context.TrimEnd(',');
            string[] originNameArray = context.Split(',');
            int nameCount = originNameArray.Length;
            string[] repeatArray = originNameArray.Distinct().ToArray();
            int repeatCount = repeatArray.Length;
            if (repeatCount < nameCount)
            {
                tb_TasterSignInClipMsg.Text = $"检测到{nameCount}个学生姓名，有{nameCount - repeatCount}个重名。";
                Color color = (Color)ColorConverter.ConvertFromString("#FFE13333");
                tb_TasterSignInClipMsg.Foreground = new SolidColorBrush(color);
                btn_Submit.IsEnabled = false;
            }
            else
            {
                tb_TasterSignInClipMsg.Text = $"检测到{nameCount}个学生姓名。";
                tb_TasterSignInClipMsg.Foreground = Brushes.Black;
                btn_Submit.IsEnabled = true;
            }
        }

        private void btn_AllSignIn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Mouse.OverrideCursor = Cursors.Wait;
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int lessonId = ((LessonSelectModel)cb_Lesson.SelectedItem).LessonId;
                string msg = "";
                if (StudentSignInApp.AllSignUpArrive(semesterId, lessonId, out msg))
                {
                    Mouse.OverrideCursor = null;
                    this.DialogResult = true;
                }

            }
            catch (Exception ex)
            {
                Mouse.OverrideCursor = null;
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
    }
}
